package com.ciwong.epaper.modules.epaper.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.MediaPlayView;
import com.ciwong.mobilelib.widget.ProgessBeakPoint;
import com.ciwong.mobilelib.widget.ProgressButtonHearing;
import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.TestWordDetail;
import com.ciwong.epaper.modules.epaper.bean.TestWordInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 报听力界面
 *
 * @author res-qqlin
 * @version ciwong v.2.0 2015/7/31
 * @since ciwong v.2.0
 */
public class TheHearingActivity extends BaseActivity {
    private static final int HANDLER_MSG_WHAT_PAUSE_SAME = 0x0000031;

    private static final int HANDLER_MSG_WHAT_PAUSE_DIFF = 0x0000032;

    private static final int INTERVAL_SAME_TIME = 2000;

    private static final int INTERVAL_DIFF_TIME = 3000;

    private static final int TEST_READING_COUNT = 1;

    private static final int HEAR_READING_COUNT = 2;

//    private String rootPath = EConstants.FILE_PREFIX + ESystem.getPackagesPath(TheHearingActivity.this)
//            + File.separator;

    private DownLoadInfo mDownLoadInfo;

    private Module mModule;

    private int position;

    private ProgressButtonHearing mMediaPlay;

    private ImageView preIv;

    private ImageView nextIv;

    private TextView mWhichTv;

    private AudioPlayer player;

    private List<String> audioPaths;

    private int mCurrentIndex;

    private boolean isPlaying = false;

    private boolean isBtnPlaying = false;

    private int audioSize;

    private MediaPlayView lineWaveView;

    private boolean isStart = true;

    private List<WordDetail> wordDetails = new ArrayList<WordDetail>();

    private TextView mMouldNameTv;

    private ProgessBeakPoint pBar;

    private int curentTimes = 0;

    private PowerManager.WakeLock mWakeLock;

    private ImageView mGoBack;


    private TextView mTitleText;

    private View btn_teacher_comment;

    private CWDialog dialog;

    private boolean isPlayComplete = false;

    private int readingCount;

    private Answer mAnswer;

    private WorkContents mWorkContents;

    private String mResourceName;
    private String packagesJsonPath;
    private long startTime;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (isFinishing()) {
                return;
            }
            switch (msg.what) {
                case HANDLER_MSG_WHAT_PAUSE_SAME:
                    try {
                        isPlaying = true;
                        player.play(audioPaths.get(mCurrentIndex));
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                            MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                            if (mMediaPlayer != null) {
                                try {
                                    PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                                    if (params != null) {
                                        mMediaPlayer.setPlaybackParams(params);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        mMediaPlay.setAudioPlayer(player);
                        mMediaPlay.start();
                        mMediaPlay.setPauseBtn();
                        opearteLineWave();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case HANDLER_MSG_WHAT_PAUSE_DIFF:
                    playNext();
                    break;
            }
        }
    };

    private ViewOnClickListener mViewOnClickListener = new ViewOnClickListener() {
        @Override
        public void avertRepeatOnClick(View v) {
            if (isFinishing()) {
                return;
            }
            int id = v.getId();
            if (id == R.id.the_hearing_go_back_img) {
                //从记录进来不需要判断是否完成

                if ((mWorkContents != null && mWorkContents.getSubmitCount() > 0) || mAnswer != null) {
                    finish();
                } else if (!isPlayComplete) {
                    showConfirmEndDialog();
                } else {
                    finish();
                }

            } else if (id == R.id.activity_hearing_pre_iv) {
                // 上一个单词
                if (mCurrentIndex > 0) {
                    mCurrentIndex--;
                    curentTimes = 0;
                    playAudio();
                    setWhichText();
                    pBar.reDraw(mCurrentIndex);
                } else {
                    showToastAlert("已经是第一个了");
                }
            } else if (id == R.id.activity_hearing_next_iv) {
                // 下一个单词
                if (mCurrentIndex < audioPaths.size() - 1) {
                    mCurrentIndex++;
                    playAudio();
                    curentTimes = 0;
                    setWhichText();
                    pBar.reDraw(mCurrentIndex);
                } else {
                    showToastAlert("已经是最后一个了");
                }
            } else if (id == R.id.activity_hearing_media_play) {
                if (isPlaying) {
                    try {
                        isPlaying = false;
                        isBtnPlaying = false;
                        player.pause();
                        opearteLineWave();
                        mMediaPlay.setPlayBtn();
                    } catch (IllegalStateException e) {

                    }
                } else {
                    if (isBtnPlaying) {
                        isBtnPlaying = false;
                        mMediaPlay.setPlayBtn();
                        mHandler.removeCallbacksAndMessages(null);
                        return;
                    } else {
                        isBtnPlaying = true;
                    }
                    isPlaying = true;
                    if (isStart) {
                        if (audioPaths.size() > 0) {

                            try {

                                player.play(audioPaths.get(mCurrentIndex));
                                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                                    MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                                    if (mMediaPlayer != null) {
                                        try {
                                            PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                                            if (params != null) {
                                                mMediaPlayer.setPlaybackParams(params);
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                                pBar.reDraw(mCurrentIndex);

                            } catch (IllegalStateException e) {

                            }


                        } else {
                            showToastError("资源不存在");
                        }
                    } else {
                        player.resume();
                    }
                    mMediaPlay.start();
                    mMediaPlay.setPauseBtn();
                    opearteLineWave();
                    isStart = false;
                }
            } else if (id == R.id.btn_teacher_comment) {

            }


        }
    };

    @Override
    protected void preCreate() {
        Intent intent = getIntent();
        if (intent != null) {
            mDownLoadInfo = (DownLoadInfo) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
            mModule = (Module) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
            position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);


            audioPaths = (List<String>) intent
                    .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);

            mAnswer = (Answer) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_ANSWER);
            mWorkContents = (WorkContents) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_WORK_CONTENTS);
        }
        /*startTime = CWSys.getSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo,mModule,position,"0"),0);
        if (startTime == 0){
            if (null != mDownLoadInfo){
                startTime = mDownLoadInfo.getStartTime();
                CWSys.setSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo,mModule,position,"0"),startTime);
            }
        }*/
    }

    @Override
    protected int setView() {
        return R.layout.activity_the_hearing;
    }

    @Override
    protected void findViews() {
        mMediaPlay = (ProgressButtonHearing) findViewById(
                R.id.activity_hearing_media_play);
        preIv = (ImageView) findViewById(R.id.activity_hearing_pre_iv);
        nextIv = (ImageView) findViewById(R.id.activity_hearing_next_iv);
        mWhichTv = (TextView) findViewById(R.id.activity_hearing_which_tx);
        lineWaveView = (MediaPlayView) findViewById(
                R.id.activity_hearing_line_wave);
        pBar = (ProgessBeakPoint) findViewById(R.id.activity_hearing_pro);
        mMouldNameTv = (TextView) findViewById(R.id.activity_hearing_name);

        mGoBack = (ImageView) findViewById(R.id.the_hearing_go_back_img);
        mTitleText = (TextView) findViewById(R.id.the_hearing_title_center);

        btn_teacher_comment = findViewById(R.id.btn_teacher_comment);
    }

    @Override
    protected void initEvent() {
        mGoBack.setOnClickListener(mViewOnClickListener);
        preIv.setOnClickListener(mViewOnClickListener);

        nextIv.setOnClickListener(mViewOnClickListener);
        mMediaPlay.setOnClickListener(mViewOnClickListener);
        btn_teacher_comment.setOnClickListener(mViewOnClickListener);

        player = AudioPlayer.getInstance();
        player.setOnPlayListener(new OnPlayListener() {
            @Override
            public void onReadPlayer(long l, Object o) {
                CWLog.i("erro", "onReadPlayer");

            }

            @Override
            public void onPlayStart(Object o) {

            }

            @Override
            public void stop(Object o) {
                if (isFinishing()) {
                    return;
                }
                // player.pause();

                isPlaying = false;
                opearteLineWave();
                mMediaPlay.setPauseBtn();
                curentTimes++;
                if (curentTimes < readingCount) {
                    mHandler.sendEmptyMessageDelayed(
                            HANDLER_MSG_WHAT_PAUSE_SAME, INTERVAL_SAME_TIME);
                } else {
                    curentTimes = 0;
                    mHandler.sendEmptyMessageDelayed(
                            HANDLER_MSG_WHAT_PAUSE_DIFF, INTERVAL_DIFF_TIME);
                    pBar.reDraw(mCurrentIndex);
                }

            }

            @Override
            public void onError(int i, Object o) {
                isPlaying = false;
                opearteLineWave();
                showToastError("资源不存在");
                mMediaPlay.setClickable(false);
            }

            @Override
            public void onBuffer(Object o, long l, long l1) {
                CWLog.i("erro", "onBuffer");
            }

            @Override
            public void onPlaying(long l, long l1) {
                CWLog.i("erro", "onPlaying");

            }
        });
        mMediaPlay.setAudioPlayer(player);
    }

    @Override
    protected void init() {
        hideTitleBar();


        if (mDownLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
            mResourceName = mDownLoadInfo.getResourceName();
            packagesJsonPath = ESystem.getPackagesJsonPathNew(mDownLoadInfo.getBookId(), mDownLoadInfo.getChapterId(), mDownLoadInfo.getModuleId(), mDownLoadInfo.getVersionId());
        } else {
            packagesJsonPath = ESystem.getPackagesJsonPath(mModule.getResourceList().get(position).getResourceFile());
            mResourceName = mModule.getResourceList().get(position).getResourceName();

        }

        mTitleText.setText(mResourceName);
        mMouldNameTv.setText(mResourceName);

        if (audioPaths == null) {
            audioPaths = new ArrayList<String>();
        }

        if (mAnswer != null && mAnswer.getComment() != null && mAnswer.getComment().length() > 0) {

            mTitleText.setText(mAnswer.getResourceName());
            btn_teacher_comment.setVisibility(View.VISIBLE);
            btn_teacher_comment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    DialogUtil.showCommentDialog(TheHearingActivity.this, mAnswer.getComment());
                }
            });


        } else if (mWorkContents != null && mWorkContents.getCommentContent() != null && !mWorkContents.getCommentContent().equals("")) {
            btn_teacher_comment.setVisibility(View.VISIBLE);
            btn_teacher_comment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogUtil.showCommentDialog(TheHearingActivity.this, mWorkContents.getCommentContent());
                }
            });

            if (null == mModule || mModule.getModuleInfo().getModuleName() == null || mModule.getModuleInfo().getModuleName().equals("")) {
                mTitleText.setText(mWorkContents.getResourceName());
            }

        } else {
            btn_teacher_comment.setVisibility(View.GONE);
        }

    }


    @Override
    protected void loadData() {
//        String packagesJsonPath = null;
        Type type = null;


        int moduleId = 0;
        if (mDownLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
            moduleId = Integer.valueOf(mDownLoadInfo.getModuleId());
        } else {
            if (mModule != null) {
                moduleId = mModule.getModuleInfo().getModuleId();
            }
        }


        switch (moduleId) {
            case ModuleInfo.ModuleInfoId.MODULE_ID_TEST:
                // ScanJumpManager.jumpCature(R.string.go_back, this,
                // mDownLoadInfo, mModule, position);
                // versionId = "634828917904286941";
                // (mModule.getResourceList().get(position)).setVersionId(versionId);

                type = new TypeToken<List<TestWordInfo>>() {
                }.getType();

                readingCount = TEST_READING_COUNT;
                break;

            case ModuleInfo.ModuleInfoId.MODULE_ID_DICTATION:
//                packagesJsonPath = ESystem.getPackagesJsonPath(mModule.getResourceList().get(position).getResourceFile());

                type = new TypeToken<List<WordDetail>>() {
                }.getType();

                readingCount = HEAR_READING_COUNT;
                break;

            case ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT:
                readingCount = TEST_READING_COUNT;
                break;
        }

        switch (moduleId) {
            case ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT:
                audioSize = audioPaths.size();
                setWhichText();
                if (audioSize > 0) {
                    pBar.setPoint(audioSize);
                    pBar.setInit();
                    pBar.invalidate();
                }
                break;

            case ModuleInfo.ModuleInfoId.MODULE_ID_TEST:
            case ModuleInfo.ModuleInfoId.MODULE_ID_DICTATION:
                final int finalModuleId = moduleId;
                EpaperDao.getInstance().getSerializableObjects(packagesJsonPath, type, new BaseExtCallBack(TheHearingActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                    @Override
                    public void failed(Object data) {
                        showToastError((int) data);
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void success(Object data) {
                        if (finalModuleId == ModuleInfo.ModuleInfoId.MODULE_ID_TEST) {
                            audioPaths.clear();
                            List<TestWordInfo> testWordInfos = (List<TestWordInfo>) data;

                            // List<TestWordDetail> attachments =
                            // testWordInfos
                            // .get(0).getAttachments();

                            for (int i = 0; i < testWordInfos
                                    .size(); i++) {
                                TestWordInfo testWordInfo = testWordInfos
                                        .get(i);

                                List<TestWordDetail> attachments = testWordInfo
                                        .getAttachments();

                                for (int j = 0; j < attachments
                                        .size(); j++) {
                                    TestWordDetail testWordDetail = attachments
                                            .get(j);

                                    audioPaths.add(
                                            (EConstants.FILE_PREFIX + ESystem.getPackagesPath(TheHearingActivity.this)
                                                    + File.separator) + testWordDetail
                                                    .getFileUrl());
                                }
                            }
                            audioSize = audioPaths.size();
                            mCurrentIndex = 0;
                            setWhichText();
                        } else {
                            wordDetails = (List<WordDetail>) data;
                            setHearingUrl();
                        }
                        if (audioSize > 0) {
                            pBar.setPoint(audioSize);
                            pBar.setInit();
                            pBar.invalidate();
                        }

                        CWLog.e("debug", wordDetails.size() + "");
                    }
                });
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWakeLock = ((PowerManager) getSystemService(Activity.POWER_SERVICE))
                .newWakeLock(
                        PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                                | PowerManager.ON_AFTER_RELEASE,
                        getPackageName());
        mWakeLock.acquire();
    }

    // @Override
    // public void onBackPressed()
    // {
    // if (!isPlayComplete)
    // {
    // showConfirmEndDialog();
    // }
    // else
    // {
    // finish();
    // }
    // }

    private void showConfirmEndDialog() {
        if (dialog == null) {
            dialog = new CWDialog(this);
            // dialog.setTitle("操作提醒");
            dialog.setMessage(R.string.confirm_back_work);
            dialog.setPositiveButton(android.R.string.cancel, null)
                    .setNegativeButton(R.string.ok,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();
                                    finish();
                                }
                            });
        }
        dialog.show();
    }

    private void playNext() {
        if (mCurrentIndex < audioPaths.size() - 1) {
            mCurrentIndex++;
            playAudio();
        } else if (curentTimes == 0) {
            isPlaying = false;
            showToastSuccess("音频播放完毕");
            opearteLineWave();
            isPlayComplete = true;
            mMediaPlay.stop();
            mMediaPlay.setPlayBtn();

            // if (mModule.getModuleInfo()
            // .getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_TEST)
            // {
            // // 跳转到拍一拍，扫答题卡，提交作业
            // ScanJumpManager.jumpCature(R.string.go_back, this,
            // mDownLoadInfo, mModule, position,
            // CameraManager.CaptureMode.ANSWERCARD);
            // finish();
            // }
        }
        setWhichText();
        pBar.reDraw(mCurrentIndex);
    }

    private void setWhichText() {
        if (audioSize > 0) {
            mWhichTv.setText(mCurrentIndex + 1 + " of " + audioSize);
        } else {
            mWhichTv.setText("0 of 0");
        }
    }

    private void playAudio() {
        if (audioPaths.size() > mCurrentIndex) {
            try {
                player.play(audioPaths.get(mCurrentIndex));
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                    MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                    if (mMediaPlayer != null) {
                        try {
                            PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                            if (params != null) {
                                mMediaPlayer.setPlaybackParams(params);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                mMediaPlay.start();
                mMediaPlay.setPauseBtn();
                isPlaying = true;
                opearteLineWave();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            showToastError(R.string.no_resources);
        }
    }

    /**
     * 线条波动
     */
    private void opearteLineWave() {
        if (isPlaying) {
            lineWaveView.play();
        } else {
            lineWaveView.stop();
        }
    }

    private void setHearingUrl() {
        audioPaths.clear();
        for (int i = 0; i < wordDetails.size(); i++) {
            audioPaths.add((EConstants.FILE_PREFIX + ESystem.getPackagesPath(TheHearingActivity.this)
                    + File.separator) + wordDetails.get(i).getWordFile());
        }
        audioSize = audioPaths.size();
        mCurrentIndex = 0;
        setWhichText();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWakeLock.release();
        try {
            player.pause();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        try {
            player.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
        mMediaPlay.release();
    }
}
